﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;

namespace Socket网络编程Client
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private Socket _socketMsg;
        /// <summary>
        /// 与服务器建立通信
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_StartConnect_Click(object sender, EventArgs e)
        {
            // 创建负责通信的Socket
            _socketMsg = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress ip = IPAddress.Parse(textBox_IP.Text);
            IPEndPoint port = new IPEndPoint(ip,int.Parse(textBox_Port.Text));
            _socketMsg.Connect(port);

            //建立连接成功
            ShowLog("建立连接成功");
        }
        /// <summary>
        /// 一种展示字符串的方式
        /// </summary>
        /// <param name="str"></param>
        private void ShowLog(string str)
        {
            textBox_RX.AppendText(str+"\r\n");
        }

        /// <summary>
        /// 将发送区的数据发送到服务器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_SendMeg_Click(object sender, EventArgs e)
        {
            byte[] sendBuff = Encoding.GetEncoding("GB2312").GetBytes(textBox_TX.Text + textBox_TX.Text.Length);
            _socketMsg.Send(sendBuff);
        }
    }
}
